package com.wzdigit.wms.wms.service.basic;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wzdigit.framework.Shift;
import com.wzdigit.mes.sys.api.UserApiService;
import com.wzdigit.mes.sys.dto.UserDto;
import com.wzdigit.wms.basic.client.PagerInfo;
import com.wzdigit.wms.basic.client.request.basic.CreateWareHouseRequest;
import com.wzdigit.wms.basic.client.request.basic.SearchWarehouseRequest;
import com.wzdigit.wms.basic.client.request.basic.UpdateStatusWareHouseRequest;
import com.wzdigit.wms.basic.client.request.basic.UpdateWareHouseRequest;
import com.wzdigit.wms.basic.client.response.Result;
import com.wzdigit.wms.basic.client.response.basic.WarehouseApiResponse;
import com.wzdigit.wms.basic.client.response.basic.WarehouseResponse;
import com.wzdigit.wms.basic.domain.basic.Warehouse;
import com.wzdigit.wms.basic.enums.BaseIsEnabledEnum;
import com.wzdigit.wms.basic.enums.FacTypeEnum;
import com.wzdigit.wms.basic.mapper.core.basic.WarehouseMapper;
import com.wzdigit.wms.basic.service.code.WhsPermService;
import com.wzdigit.wms.basic.util.HttpSessionUtil;
import com.wzdigit.wms.common.entity.StatusCode;
import com.wzdigit.wms.wms.domain.dto.FacDto;
import net.dreamlu.mica.core.utils.BeanUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 仓库 服务类
 * @author yangdongjie
 * @WarehouseService.java
 * @2021年1月4日上午11:13:55
 */
@Service
public class WarehouseService {

    @Autowired
    private WarehouseMapper warehouseMapper;
    
    @Autowired
	private WhsPermService whsPremService;
    
    @Autowired
	private WhsPermService whsCodeService;
    
    @Reference(version = "${dubbo.consumers.sys.user.api.version:1.0.0}", check = false, timeout = 300000)
    private UserApiService userApiService;

	//查询可用仓库列表
	public List<WarehouseApiResponse> list() {
		return warehouseMapper.selectAllByStatus(BaseIsEnabledEnum.USE.code);
	}

	//查询可用+禁用仓库列表
	public List<WarehouseApiResponse> listAll() {
		return warehouseMapper.selectAllByStatus(null);
	}
    
    public WarehouseResponse getWarehouse(Integer whsId) {
    	return warehouseMapper.selectOneByWhsId(whsId);
    }
    
    public Warehouse selectById(Integer whsId) {
    	return warehouseMapper.selectById(whsId);
    }
    
    /**
	 * 获取当前用户权限的仓库ID
	 * 
	 * @param servletRequest
	 * @return
	 */
    public List<Integer> getWareHouseIds(HttpServletRequest servletRequest) {
		return whsPremService.getWareHouseIds(servletRequest);
 	}
    
    /**
	 * 获取当前用户权限的仓库
	 * 
	 * @param servletRequest
	 * @return
	 */
	public List<WarehouseApiResponse> getWarehousePerm(Integer whsType, HttpServletRequest servletRequest) {
		return whsPremService.getWarehousePerm(whsType, servletRequest);
	}
    
    @SuppressWarnings("rawtypes")
	public <T> PagerInfo<List<WarehouseResponse>> searchWarehouse(SearchWarehouseRequest dto, 
			HttpServletRequest servletRequest) {
    	List<Integer> whsIdList = null;
    	if (dto.getIsOneselfPerm() != null && dto.getIsOneselfPerm()) {
    		String userName = HttpSessionUtil.getLoginName(servletRequest);
            whsIdList = whsCodeService.getWareHouseIds(userName);
    	}
    	Page<T> page = PageHelper.offsetPage(dto.getSkipCount(), dto.getMaxResultCount());
        PagerInfo<List<WarehouseResponse>> pagerInfo = new PagerInfo<List<WarehouseResponse>>();
        List<WarehouseResponse> list = warehouseMapper.selectAll(dto, whsIdList);
        pagerInfo.setItems(list);
        pagerInfo.setTotalCount(page.getTotal());
		return pagerInfo;
    }
    
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public WarehouseResponse createWareHouse(CreateWareHouseRequest dto,
    		HttpServletRequest servletRequest) {
    	String loginName = HttpSessionUtil.getLoginName(servletRequest);
    	Warehouse warehouse = warehouseMapper.selectOneByWhsCode(dto.getWhsCode());
    	if(warehouse != null) {
    		// 编码已存在
    		Shift.fatal(StatusCode.CODE_DATA_EXIST);
    	}
    	warehouse = new Warehouse();
    	BeanUtil.copyNonNull(dto, warehouse);
    	warehouse.setCreateUser(loginName);
    	warehouse.setCreateTime(new Date());
    	warehouseMapper.insert(warehouse);
    	
    	WarehouseResponse response = new WarehouseResponse();
    	BeanUtil.copyNonNull(warehouse, response);
		return response;
    }
    
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public WarehouseResponse updateWareHouse(UpdateWareHouseRequest dto,
    		HttpServletRequest servletRequest) {
    	String loginName = HttpSessionUtil.getLoginName(servletRequest);
    	Warehouse warehouse = warehouseMapper.selectOneByWhsCode(dto.getWhsCode());
    	if(warehouse != null) {
    		if (dto.getWhsId().intValue() != warehouse.getWhsId().intValue()) {
    			// 编码已存在
    			Shift.fatal(StatusCode.CODE_DATA_EXIST);
			}
    	}
    	warehouse = warehouseMapper.selectByPrimaryKey(dto.getWhsId());
    	BeanUtil.copy(dto, warehouse);
    	warehouse.setModifyUser(loginName);
    	warehouse.setModifyTime(new Date());
    	warehouseMapper.updateById(warehouse);
    	
    	WarehouseResponse response = new WarehouseResponse();
    	BeanUtil.copy(warehouse, response);
		return response;
    }
    
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public <T> Result<T> updateStatus(UpdateStatusWareHouseRequest dto,
    		HttpServletRequest servletRequest) {
    	String loginName = HttpSessionUtil.getLoginName(servletRequest);
    	Warehouse warehouse = warehouseMapper.selectByPrimaryKey(dto.getWhsId());
    	warehouse.setStatus(dto.getStatus());
    	warehouse.setModifyUser(loginName);
    	warehouse.setModifyTime(new Date());
    	warehouseMapper.updateStatus(warehouse);
		return new Result<>();
    }

    /**
     * 根据仓库ID集合获取仓库信息
     * @param whsIdList
     * @return
     */
	public List<Warehouse> findByWhsIdListList(List<Integer> whsIdList) {
        QueryWrapper<Warehouse> wrapper = new QueryWrapper<>();
        wrapper.in("WHS_ID",whsIdList);

        List<Warehouse> warehouseList = warehouseMapper.selectList(wrapper);
        return warehouseList;
    }

	/**
	 * 根据主键查询仓库信息
	 * @param fmWhs
	 * @return
	 */
	public Warehouse selectByPK(Integer fmWhs) {
		Warehouse warehouse = warehouseMapper.selectById(fmWhs);
		return warehouse;
	}

	public List<FacDto> getFacDto() {
		Map<String, String> facMap = FacTypeEnum.getEnumByDescription();
		List<FacDto> list=new ArrayList<>();
		for (Map.Entry<String, String> entry : facMap.entrySet()) {
			FacDto dto=new FacDto();
			dto.setFacType(entry.getKey());
			dto.setFacValue(entry.getValue());
			list.add(dto);
		}
		return list;
	}

}
